﻿#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>

//结构体内存对齐
struct S
{
	char c1;//1
	int i;//4
	char c2;//1
};

struct S2
{
	char c1;
	char c2;
	int i;
};

struct S3
{
	double d;
	char c;
	int i;
};

//结构体嵌套
struct S4
{
	char c1;
	struct S3 s3;//成员最大对齐数
	double d;
};

int main()
{
	struct S s = { 0 };
	struct S2 s2 = { 0 };
	struct S3 s3 = { 0 };
	struct S4 s4 = { 0 };
	printf("%zd\n", sizeof(s));//size_t 12
	printf("%zd\n", sizeof(s2));//8  
	printf("%zd\n", sizeof(s3));//16  
	printf("%zd\n", sizeof(s4));//32  

	return 0;
}



//修改对齐数
//
#pragma pack(1)
struct S
{
	char c1;//1
	int i;//4
	char c2;//1
};
#pragma pack()

int main()
{
	printf("%zd\n", sizeof(struct S));

	return 0;
}



//结构体传参
//
struct S
{
	int arr[1000];
	int n;
	double d;
};

void show_struct1(struct S temp)
{
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", temp.arr[i]);
	}
	printf("%d ", temp.n);
	printf("%lf\n", temp.d);
}

void show_struct2(struct S* ps)
{
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("%d ", ps->n);
	printf("%lf\n", ps->d);
}

int main()
{
	struct S s = { {1,2,3,4,5},100,3.14 };
	show_struct1(s);
	show_struct2(&s);

	return 0;
}



//位段式的结构 - 节省空间
struct S
{
	int _a:2;//a取值很小，只占2个bit位
	int _b:5;//只占5个bit位
	int _c:10;//只占10个bit位
	int _d:30;//只占30个bit位
};

int main()
{
	printf("%zd\n", sizeof(struct S));

	return 0;
}


//⼀个例子
struct S
{
	char a:3;
	char b:4;
	char c:5;
	char d:4;
	};

int main()
{
	struct S s = { 0 };
	s.a = 10;//010
	s.b = 12;//1100
	s.c = 3;//00011
	s.d = 4;//0100
	printf("%zd\n", sizeof(struct S));

	return 0;
}




struct A
{
	int _a : 2;
	int _b : 5;
	int _c : 10;
	int _d : 30;
};
int main()
{
	struct A sa = { 0 };
	scanf("%d", &sa._b);//这是错误的

	//正确的⽰范
	int b = 0;
	scanf("%d", &b);
	sa._b = b;

	return 0;
}


//联合体

union Un
{
	char c;//1
	int i;//4
};

int main()
{
	union Un u = { 0 };
	//printf("%zd\n", sizeof(u));//4
	//printf("%p\n", &u);
	//printf("%p\n", &(u.i));
	//printf("%p\n", &(u.c));

	u.i = 0x11223344;
	u.c = 0x55;

	return 0;
}



union Un
{
	char c1[5];//5
	short c2[7];//14
	int i;//4
};

int main()
{
	union Un u = { 0 };
	printf("%zd\n", sizeof(u));//16

	return 0;
}


//联合体举例

struct shop_list
{
	int stock_number;//库存
	double price;//价格
	int item_type;//商品类型
	union 
	{
		struct
		{
			char title[20];//书名
			char author[20];//作者
			int num_pages;//⻚数
		}book;
		struct
		{
			char design[30];//设计
		}mug;
		struct
		{
			char design[30];//设计
			int colors;//颜⾊
			int sizes;//尺⼨
		}shirt;
	}item;
};

int main()
{
	struct shop_list gl;
	gl.item.mug.design;

	return 0;
}


//联合体方式判断大小端

//int check_keys()
//{
//	int n = 1;
//	return *(char*)&n;
//}

int check_keys()
{
	union Un
	{
		char c;
		int i;
	}u;
	u.i = 1;
	return u.c;
}

int main()
{
	int ret = check_keys();
	if (ret)
	{
		printf("小端\n");
	}
	else
	{
		printf("大端\n");
	}

	return 0;
}